package cn.iver.controller;

import cn.iver.common.WebUtils;
import cn.iver.interceptor.UserCheckInterceptor;
import cn.iver.model.User;
import cn.iver.validator.LoginValidator;
import cn.iver.validator.RegistValidator;
import cn.iver.validator.UpdateUserValidator;

import java.io.File;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.render.JsonRender;
import com.jfinal.upload.UploadFile;

/**
 * Created with IntelliJ IDEA.
 */
public class UserController extends Controller {
    public void index(){
        setAttr("user", User.dao.get(getParaToInt(0, 0)));
        render("/user/user.html");
    }

    @Before(LoginValidator.class)
    public void login(){
        String email = getPara("email");
        String password = getPara("password");
        User user = User.dao.getByEmailAndPassword(email, password);
        if (user != null){
            WebUtils.loginUser(this, user, true);
            redirect("/");
        }else{
            setAttr("msg", "用户名或密码错误");
            render("/user/login.html");
        }
    }

    public void logout(){
        WebUtils.logoutUser(this);
        redirect("/");
    }

    @Before(RegistValidator.class)
    public void save(){
        User user = getModel(User.class);
        user.mySave();
        setAttr("msg", "恭喜你，注册成功，请登录：");
        render("/user/login.html");
    }

    @Before(UserCheckInterceptor.class)
    public void edit(){
        setAttr("user", User.dao.get(getParaToInt(0, 0)));
        render("/user/edit.html");
    }

    @Before({ UserCheckInterceptor.class, UpdateUserValidator.class })
    public void update(){
        User user = getModel(User.class);
        user.myUpdate();
        setAttr("user", user);
        render("/user/user.html");
    }

	/**
	 * 文件上传
	 */
    public void editor(){
        String rootPath = PathKit.getWebRootPath();
        try {
            UploadFile file = getFile("imgFile");
            User user = WebUtils.currentUser(this);
            if (null == user) {
                setAttr("error", 1);
                setAttr("message", "上传出错，请先登陆！");
                render(new JsonRender(new String[]{"error", "message"}).forIE());
                return;
            }
            //String type = getPara("dir"); //辨别 图片，zip，电影以及其他，自己不想去折腾了
            String fileName = file.getFileName();
            String fileType = getFileType(fileName);
            String newName = System.currentTimeMillis() + fileType;
            // 第一次上传文件
            String filePath = rootPath + "/upload/" + newName;
            // 删除本地临时文件
            file.getFile().renameTo(new File(filePath));
            // 返回json
            setAttr("error", 0);
            setAttr("url", "/upload/" + newName);
            render(new JsonRender(new String[]{"error", "url"}).forIE());
        } catch (Exception e) {
            setAttr("error", 1);
            setAttr("message", "上传出错，请稍候再试！");
            render(new JsonRender(new String[]{"error", "message"}).forIE());
        }
    }

    /**
     * 获取文件类型
     * @param @param fileName
     * @param @return    设定文件
     * @return String    返回类型
     * @throws
     */
    private static String getFileType(String fileName){
        return fileName.substring(fileName.lastIndexOf('.'), fileName.length());
    }
}
